<template>
  <!-- components: DropDown -->
  <div class = "dropdown" ref = "dropdownRef">
    <a
      class = "btn btn-outline-light my-2 dropdown-toggle"
      v-on:click.prevent ="toggleOpen"
    >{{title}}</a>
    <ul
      class = "dropdown-menu"
      v-if ="isOpen"
      v-bind:style ="{display:'block'}"
    >
      <slot></slot>
    </ul>
  </div>
</template>

<script lang = "ts">
import { defineComponent, ref, watch } from 'vue'
// 导入自定义函数
import useClickOutside from '@/hooks/useClickOutside'

// 对setup函数进行封装，返回options的对象
export default defineComponent({
  // 页面名称
  name: 'DropDown',
  // 传递数据
  props: {
    title: {
      type: String,
      required: true
    }
  },

  // 组合式api的入口
  setup () {
    // 注册引用信息
    const isOpen = ref(false)
    // 获取dom节点
    const dropdownRef = ref<null | HTMLElement>(null)
    // 导航栏按钮
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }
    const isClickOutside = useClickOutside(dropdownRef)
    // 监听变化
    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside.value) {
        isOpen.value = false
      }
    })

    return {
      isOpen,
      toggleOpen,
      dropdownRef
    }
  }
})
</script>

<style lang = "css" scoped>
</style>
